<?php
class Admin_articleController extends Controller {
    
        /**
         * 定义布局视图
         * 
         * @var string
         */    
		protected function before() {
			
			$this->set_layout('admin_main');
		}

        /**
        * 后台管理：文章列表页
        */
        public function indexAction() {
            //判断登陆
            auth::parse_login();
            
            //获取参数
            $page = $this->get('page');
            $page = (!$page) ? 1 : (int)$page;
            
            //实例化model
            $post_model = $this->model('posts');
            
            //定义列表显示的行数
            $page_list_num = 10;
            
            //获取列表数据
            $post_data = $post_model->from('posts', array('post_id', 'post_author', 'post_title', 'date_added'))->where('post_type=0')->order('post_id desc')->page_limit($page, $page_list_num)->select();
            
            $list_array = array();
            if ($post_data) {
                foreach ($post_data as $key=>$lines) {
                    $list_array[$key]['id']     = $lines['post_id'];
                    $list_array[$key]['title']  = $lines['post_title'];
                    $list_array[$key]['time']   = $lines['date_added'];
                    $author_data = $post_model->from('admin_users', array('user_name'))->where('user_id=' . $lines['post_author'])->select(false);
                    $list_array[$key]['author'] = $author_data['user_name'];
                }
            }
            
            //分页处理
            $pagelist       = $this->instance('pager');
            $list_total_num = $post_model->count('posts', 'post_id', 'post_type=0');
            
            //assign params
            $this->assign(array(
                'site_name'     => '文章列表',
                'list_data'     => $list_array,
                'pagelist_css'  => $pagelist->load_css('classic'),
                'pagelist_html' => $pagelist->total($list_total_num)->num($page_list_num)->page($page)->url($this->get_self_url() . '/?page=')->output(),
                'page'          => $page,
            ));
            
            //display page
            $this->display();
        }
        
        /**
         * thickbox ajax加载文章编辑页面
         */
        public function ajax_tb_edit_articleAction() {
            //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $post_id = (int)$this->get('id');
            $page    = (int)$this->get('page');
            if (!$post_id) {
                exit ();
            }
            
            //实例化model
            $post_model     = $this->model('posts');
            $tag_model      = $this->model('tags');
            $meta_model     = $this->model('post_meta');
            
            $post_data      = $post_model->find($post_id);
            $meta_data      = $meta_model->find($post_id);
            
            //获取分类信息
            $term_data = $post_model->from('terms', array('term_id', 'term_name'))->order('term_id asc')->select();
            $class_array = array('0'=>'未分类');
            foreach ($term_data as $lines) {
                $class_array[$lines['term_id']] = $lines['term_name'];
            }
            
            //获取标签信息
            $tag_data   = $tag_model->from('post_tags', 'tag_id')->where('post_id=' . $post_id)->select();
            $tag_str    = '';
            if ($tag_data) {
                $tag_name_array = array();
                foreach ($tag_data as $lines) {
                    $tag_name_data      = $tag_model->find($lines['tag_id']);
                    $tag_name_array[]   = $tag_name_data['tag_name'];
                }
                $tag_str = implode(',', $tag_name_array);
                unset ($tag_name_array);
            }
            
            //实例化编辑器
            $editor = $this->module('kindeditor');
            
            $this->assign(array(
                'site_name'     => '编辑文章',
                'post_id'       => $post_id,
                'post_data'     => $post_data,
                'meta_data'     => $meta_data,
                'tag_str'       => $tag_str,
                'class_array'   => $class_array,
                'editor_js'     => $editor->get_simple_editor('content_box'),
                'page'          => $page,
            ));
            
           //显示页面
           $this->display();
        }
        
        /**
         * ajax处理文章编辑
         */
        public function ajax_edit_articleAction() {
             //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $id             = (int)$this->post('post_id');
            $title          = $this->post('title_box');
            //对富文本内容进行XSS代码过滤,不然你就悲剧了
            $content        = trim(text::remove_xss($_POST['content_box']));
            $class          = (int)$this->post('class_box');           
            $type           = (int)$this->post('type_box');
            $tag            = $this->post('tag_box');
            $key_words      = $this->post('meta_keyword_box');
            $description    = $this->post('meta_description');
            
            //分析参数
            if (!$id || !$title || !$content) {
                exit ();
            }
                                    
            //实例化model
            $post_model = $this->model('posts');
            
            $update_post_array = array(
               'post_class'     => $class,
               'post_status'    =>$type,
               'post_title'     => $title,
               'post_content'   =>$content,
               'date_modified'  => date('Y-m-d H:i:s'),
            );
            
            if (!$post_model->update($update_post_array, 'post_id=' . $id)) {
                echo 100;
                exit ();
            }
            
            //处理关键词,简介
            if ($key_words || $description) {
                $meta_model = $this->model('post_meta');
                $check_meta_data = $meta_model->find($id, array('post_id'));
                //当meta数据表中有相关数据,则更改meta内容,否则添加meta数据
                if ($check_meta_data) {
                    if($key_words) {
                        $update_meta_array['meta_keyword'] = $key_words;
                    }
                    if($description) {
                        $update_meta_array['meta_description'] = $description;
                    }
                    $meta_model->update($update_meta_array, 'post_id=' . $id);
                    
                } else {
                   $insert_meta_array['post_id']  = $id;
                   if ($key_words) {
                       $insert_meta_array['meta_keyword'] = $key_words;
                   }
                   if ($description) {
                       $insert_meta_array['meta_description'] = $description;
                   }
                   $meta_model->insert($insert_meta_array);
                }
            }
            
            //处理标签数据
            $post_tag_model = $this->model('post_tags');
            $post_tag_data = $post_tag_model->getAll('post_id=' . $id, null, array('tag_id'));
            if ($post_tag_data || $tag) {
                $tag_model      = $this->model('tags');
                //先删除文章原来的标签
                if($post_tag_data) {
                    foreach ($post_tag_data as $rows) {
                        $tag_data = $tag_model->find($rows['tag_id'], array('tag_id', 'count'));
                        if($tag_data['count'] > 1) {
                            $tag_model->update(array('count'=>$tag_data['count'] - 1), 'tag_id=' . $rows['tag_id']);
                        } else {
                            $tag_model->delete('tag_id=' . $rows['tag_id']);
                        }
                    }
                    $post_tag_model->delete('post_id=' . $id);
                }
                
                //添加新标签
                if ($tag) {
                    $tag        = str_replace('，', ',', $tag);
                    $tag_array  = explode(',', $tag);
                    
                     foreach ($tag_array as $tag_name) {
                         $tag_name = trim($tag_name);
                         
                         $tag_id_data = $tag_model->getOne('tag_name=?', $tag_name, array('tag_id'));
                         
                         if ($tag_id_data) {
                             $tag_id = $tag_id_data['tag_id'];
                         } else {
                             $tag_model->insert(array('tag_name'=>$tag_name));
                             $tag_id = $tag_model->get_insert_id();
                         }
                         
                         $post_tag_model->insert(array('post_id'=>$id, 'tag_id'=>$tag_id));
                     }
                }                                               
            }
            
            echo 101;
        }

        /**
         * AJAX处理删除文章操作
         */
        public function ajax_delete_articleAction() {
            //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $mode       = (int)$this->post('mode');
            $list_id    = $this->post('list_id');
            $list_id    = ($mode == 1) ? $list_id : (int)$list_id;
            if (!$list_id) {
                exit ();
            }
           
            $delete_list_array = ($mode == 1) ? explode(',', $list_id) : array($list_id);
            
            //实例化model
            $post_model = $this->model('posts');
            $tag_model  = $this->model('tags');
            $meta_model = $this->model('post_meta');
            
            foreach ($delete_list_array as $post_id) {                
                 if(!$post_model->delete('post_id=' . $post_id)) {
                    echo 100; 
                    exit ();
                }
                
                //删除相关的meta数据
                $meta_model->delete("post_id=" . $post_id);
                
                //删除相关的标签
                $tag_data = $tag_model->from('post_tags', 'tag_id')->where('post_id=' . $post_id)->select();
                if (!$tag_data) {
                    continue;
                }
                foreach ($tag_data as $lines) {
                    $tag_count_data = $tag_model->find($lines['tag_id']);
                    if ($tag_count_data['count'] > 1) {
                        $tag_model->execute("UPDATE `tags` SET `count`=`count`-1 WHERE `tag_id` ={$lines['tag_id']}");
                    } else {
                        $tag_model->delete('tag_id=' . $lines['tag_id']);
                    }
                }
                $post_model->execute("DELETE FROM `post_tags` WHERE `post_id` = {$post_id}");
            }
            
            echo 101;
        }

                /**
         * 后台管理：添加新文章页面
         */
        public function insert_newAction() {
            //判断登陆
            auth::parse_login();
            
            //实例化model
            $model = $this->model('terms');
            
            //获取分类信息
            $term_data = $model->from('terms', array('term_id', 'term_name'))->order('term_id asc')->select();
            $class_array = array('0'=>'未分类');
            foreach ($term_data as $lines) {
                $class_array[$lines['term_id']] = $lines['term_name'];
            }
            
            $admin_login_data = cookie::get('smile_admin_login');
            
            //实例化编辑器
            $editor = $this->module('kindeditor');
                        
             //assign params
            $this->assign(array(
                'site_name' => '添加新文章',
                'editor_js' => $editor->get_simple_editor('content_box'),
                'class_data'=> $class_array,
                'user_id'   => $admin_login_data['user_id'],
            ));
            
            //display page
            $this->display();
        }
        
        /**
         * AJAX处理添加新文章
         */
        public function ajax_insert_newAction() {
            //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $title          = $this->post('title_box');
            //对富文本编辑内容进行XSS内容过滤,安全第一,必须的
            $content        = trim(text::remove_xss($_POST['content_box']));
            $class          = (int)$this->post('class_box');
            $author         = (int)  $this->post('author_box');
            $type           = (int)$this->post('type_box');
            $tag            = $this->post('tag_box');
            $key_words      = $this->post('meta_keyword_box');
            $description    = $this->post('meta_description');
            
            //分析参数
            if (!$title || !$content) {
                exit ();
            }
                                    
            //实例化model
            $post_model = $this->model('posts');             
             
            $insert_post_array = array(
               'post_author' => $author,
               'post_type'   => 0,
               'post_class' => $class,
               'post_status'=>$type,
               'post_title' => $title,
               'post_content'=>$content,
               'date_added' => date('Y-m-d H:i:s'),
            );
            
            if(!$post_model->insert($insert_post_array)) {
                echo 100;
                exit ();
            }
           
            //获取文章ID
            $post_id = $post_model->get_insert_id();
            
            //添加文章的搜索关键词及简介
            if ($key_words || $description) {                
                $meta_model = $this->model('post_meta');
                
                $insert_meta_array = array('post_id'  => $post_id);
                if ($key_words) {
                    $insert_meta_array['meta_keyword'] = $key_words;
                }
                if ($description) {
                    $insert_meta_array['meta_description'] = $description;
                }
                
                $meta_model->insert($insert_meta_array);
            }
           
            //处理标签
            if ($tag) {
                //将汉字的逗号替换为英文的逗号
                $tag       = str_replace('，', ',', $tag);
                //用逗号分割标签并分析处理
                $tag_array = explode(',', $tag);
                foreach ($tag_array as $tag_name) {
                    $tag_name = trim($tag_name);
                    
                    $tag_model = $this->model('tags');
                    
                    $check_tag_data = $tag_model->getOne('tag_name=?', $tag_name, array('tag_id'));
					
                    if ($check_tag_data) {
                        $tag_model->execute("UPDATE `tags` SET `count`=`count`+1 WHERE `tag_id` ={$check_tag_data['tag_id']}");

                        $tag_id = $check_tag_data['tag_id'];
                    } else {
                        $tag_model->insert(array('tag_name'=>$tag_name));
                        $tag_id = $tag_model->get_insert_id();
                    }
                   
                   $tag_model->execute("INSERT INTO `post_tags` (`post_id` ,`tag_id`) VALUES ('{$post_id}', '{$tag_id}')") ;
                }
            }
            
            echo 101;
        }

                /**
         * 后台管理：文章分类管理页面
         */
        public function termAction() {
            //判断登陆
            auth::parse_login();
            
            //instance model
            $model = $this->model('terms');
            
            //get term data
            $term_data = $model->findAll();
            
            $list_array = array();
            foreach ($term_data as $key=>$lines) {
                $list_array[$key]['id']     = $lines['term_id'];
                $list_array[$key]['name']   = $lines['term_name'];
                $list_array[$key]['note']   = $lines['term_note'];
                $article_nums = $model->execute("SELECT COUNT(`post_id`) AS `total_num` FROM `posts` WHERE `post_class` ={$lines['term_id']}", false);
                $list_array[$key]['num']    = $article_nums['total_num'];
            }
            
             //assign params
            $this->assign(array(
                'site_name' => '文章分类',
                'list_data' => $list_array,
            ));
            
            //display page
            $this->display();
        }
        
        /**
         * AJAX添加文章分类
         */
        public function ajax_insert_termAction() {
            //判断登陆
            auth::parse_login(true);
            
            //get params
            $term_name = $this->post('term_name');
            $term_note = $this->post('term_note');
            if (!$term_name) {
                exit ();
            }
            
            //instance model
            $term_model = $this->model('terms');
            
            //判断所在添加的分类是否已存在
            $check_data = $term_model->getOne('term_name=?', $term_name);
            if (!$check_data) {
                $insert_array['term_name'] = $term_name;
                if ($term_note) {
                     $insert_array['term_note'] = $term_note;
                }
                if($term_model->insert($insert_array)) {
                    echo 101;
                } else {
                    echo 100;
                }                
            } else {
                echo 103;
            }
        }
        
        /**
         * AJAX删除文章分类
         */
        public function ajax_delete_termAction() {
            //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $term_id = $this->post('id');
            if (!$term_id) {
                exit ();
            }
            
            //实例化model
            $term_model = $this->model('terms');
            
            //在删除之前，查询一下在文章中有没有所要删除分类的文章.如果有文章属于该分类,则不能删除
            $check_data = $term_model->execute("SELECT COUNT(`post_id`) AS `total_num` FROM `posts` WHERE `post_class` ={$term_id}", false);
            if ($check_data['total_num'] > 0) {
                exit ();
            }
            
            if($term_model->delete('term_id=' . $term_id)) {
                echo 101;
            } else {
                echo 100;
            }
        }
        
        /**
         * thickbox通过ajax加载分类编辑页面
         */
        public function ajax_tb_edit_termAction() {
             //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $term_id   = $this->get('id');
            if (!$term_id) {
                exit ();
            }
            
            //实例化model
            $term_model = $this->model('terms');
            
            $data = $term_model->getOne('term_id=' . $term_id);
            
            include $this->view();
        }

                /**
         * AJAX更改文章分类
         */
        public function ajax_edit_termAction() {
            //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $term_id   = $this->post('term_id');
            $term_name = $this->post('term_name');
            $term_note = $this->post('term_note');
            if (!$term_id || !$term_name) {
                exit ();
            }
            
            //实例化model
            $term_model = $this->model('terms');
            
            //查询一下编辑后的分类是否已存在
            $check_data = $term_model->from('terms', 'term_id')->where('term_name=?', $term_name)->where('term_id !=' . $term_id)->select(false);
            if ($check_data) {
                echo 103;
                exit ();
            }
            
            $update_array = array('term_name'=>$term_name);
            if ($term_note) {
                $update_array['term_note'] = $term_note;
            }
            
            if ($term_model->update($update_array, 'term_id=' . $term_id)) {
                echo 101;
            } else {
                echo 100;
            }
        }

        /**
         * 后台管理:标注管理页面
         */
        public function tagAction() {
            //判断登陆
            auth::parse_login();
            
            //获取参数
            $page = $this->get('page');
            $page = (!$page) ? 1 : (int)$page;
            
            //实例化model
            $tag_model = $this->model('tags');
            
            //定义每页显示的标签列表数
            $page_list_num = 10;
            
            $tag_data = $tag_model->from('tags')->order('count desc')->page_limit($page, $page_list_num)->select();
            
            //处理分页
            $pagelist = $this->instance('pager');
            
            $total_num_data = $tag_model->count('tags', 'tag_id');
            
            //assign params
            $this->assign(array(
                'site_name' => '标签管理',
                'list_data' => $tag_data,
                'pagelist_css' => $pagelist->load_css('classic'),
                'pagelist_html' => $pagelist->url($this->get_self_url() . '/?page=')->num($page_list_num)->page($page)->total($total_num_data)->output(),
            ));
            
            //display page
            $this->display();
        }
        
        /**
         * AJAX删除标签
         */
        public function ajax_delete_tagAction() {
            //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $mode = (int)$this->post('mode');
            $list_id = $this->post('list_id');
            $list_id = ($mode == 1) ? $list_id : (int)$list_id;
            if(!$list_id) {
                exit ();
            }
                       
            $list_id_array = ($mode == 1) ? explode(',', $list_id) : array($list_id);
            
            //实例化model
            $tag_model      = $this->model('tags');
            $post_tag_model = $this->model('post_tags');
            
            $result_status = false;
            foreach ($list_id_array as $tag_id) {
                if($post_tag_model->delete('tag_id=' . $tag_id)){
                    $result_status = $tag_model->delete('tag_id=' . $tag_id);
                }
                if(!$result_status) {
                    break;
                }
            }
            
            echo ($result_status == true) ? 101 : 100;
        }
        
        /**
         * thickbox通过ajax调用编辑标签页
         */
        public function ajax_tb_edit_tagAction() {
            //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $tag_id = (int)$this->get('id');
            if(!$tag_id) {
                exit ();
            }
            
            //实例化model
            $tag_model = $this->model('tags');
            $tag_data  = $tag_model->find($tag_id);
            
            //加载视图
            include $this->view();
        }
        
        /**
         * AJAX编辑标签
         */
        public function ajax_edit_tagAction() {
             //判断登陆
            auth::parse_login(true);
            
            //获取参数
            $tag_id     = (int)$this->post('tag_id');
            $tag_name   = $this->post('tag_name');
            if (!$tag_id || !$tag_name) {
                exit ();
            }
            
            //实例化model
            $tag_model = $this->model('tags');
            
            //查询所要编辑的标签是否已存在
            $check_tag_data = $tag_model->from('tags', 'tag_id')->where('tag_name=?', $tag_name)->where('tag_id!=' . $tag_id)->select(false);
            
            if($check_tag_data) {
                echo 103;
                exit ();
            }
            
            echo $tag_model->update(array('tag_name'=>$tag_name), 'tag_id=' . $tag_id) ? 101 : 100;
        }       
}